from datetime import datetime
from sqlalchemy import Column, Integer, String, SmallInteger, orm
from werkzeug.security import generate_password_hash, check_password_hash
from app.libs.error_code import AuthFailed
from app.models.base import Base, db


class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    nickname = Column(String(24), nullable=True, unique=True)
    email = Column(String(50), unique=True, nullable=False)
    auth = Column(SmallInteger, default=1)
    _password = Column('password', String(100))

    @orm.reconstructor
    def __init__(self):
        self.fields = ['id', 'nickname', 'email', 'auth']

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    @staticmethod
    def create_user(nickname, email, password):
        with db.auto_commit():
            user = User()
            user.nickname = nickname
            user.email = email
            user.password = password
            db.session.add(user)

    @staticmethod
    def verify(email, password):
        user = User.query.filter_by(email=email).first_or_404()
        if not user.verify_password(password):
            raise AuthFailed(msg='密码错误')
        scope = 'AdminScope' if user.auth == 2 else 'UserScope'
        return {'uid': user.id, 'scope': scope}

    def verify_password(self, raw):
        return check_password_hash(self.password, raw)